//
//  WCNCreateMeetingVC.m
//  WCN
//
//  Created by wsj2015 on 16/5/25.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNCreateMeetingVC.h"
#import "WCNMeetingPeopleCell.h"
#import "WCNAddCell.h"
#import "WCNMeetingHeaderCell.h"
#import "WCNMeetingfooterBtn.h"
#import "WCNHospitalListVC.h"
#import "WCNNurseModel.h"
#import "JCAlertView.h"

#import "WCNZhumuManager.h"
#import "Masonry.h"
#import "WCNAppDelegate.h"
@interface WCNCreateMeetingVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong)UICollectionView  *collectionView;
@property (nonatomic, copy) NSString  *meetID;
@property (nonatomic, strong) NSMutableArray  *dataArray;


@end

@implementation WCNCreateMeetingVC
- (instancetype)init
{
    self = [super init];
    if (self) {
       
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = kAppBg;
    self.title = @"我的会议";
    [self.view addSubview:self.collectionView];
    defineWeakSelf;
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
   
    
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0);

    [self getZhumuData];
    
}

- (void)getZhumuData {

    
    [[WCNZhumuManager shareManager] getZhumuDataWithLoginNumber:_email completionBlock:^(id obj) {
        _meetID = obj;
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathWithIndex:0]]];
    }];
    
    
//    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
//    //    NSDictionary *param = @{@"userName":mobile};
//    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
//    NSDictionary *parameters = @{@"api_key":kAPI_KEY, @"api_secret":kAPI_SECRET, @"logintype":@3,@"loginname":_email};
//    defineWeakSelf;
//   [sessionManager POST:@"https://api.zhumu.me/v1/user/get" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *result = responseObject;
//       _meetID = result[@"pmi"];
//       [weakSelf.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathWithIndex:0]]];
//        [hud hide:YES];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//         [hud hide:YES];
//    }];


}
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray =[NSMutableArray array];
    }
   
    return _dataArray;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    WCNAppDelegate *delegate = (WCNAppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.isMeetingNow = NO;
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}
- (void)pageBack {
    WCNAppDelegate *delegate = (WCNAppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.isMeetingNow = NO;
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    [super pageBack];

}

//开始会议
- (void)createMeeting
{
    WCNAppDelegate *delegate = (WCNAppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.isMeetingNow = YES;
    [[WCNZhumuManager shareManager] creatMeetingWithNumber:_email vc:self];
}


- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout =[[UICollectionViewFlowLayout alloc]init];
        CGFloat w = 72;
        CGFloat h = 42;
        layout.itemSize =CGSizeMake(w, h);
//        间距
        layout.sectionInset =UIEdgeInsetsMake(0, 10, 0, 10);
        
        layout.minimumInteritemSpacing =(kScreenWidth - 72*2-64 -20)/2 -4;
        layout.minimumLineSpacing = 18;
        CGRect frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight);
//        _collectionView =[[UICollectionView alloc]initWithFrame:frame collectionViewLayout:layout];
        _collectionView =[[UICollectionView alloc]initWithFrame:frame collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        _collectionView.alwaysBounceVertical =YES;
        _collectionView.backgroundColor = kAppBg;
        [_collectionView registerNib:[UINib nibWithNibName:@"WCNMeetingPeopleCell" bundle:nil] forCellWithReuseIdentifier:@"WCNMeetingPeopleCell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"WCNAddCell" bundle:nil] forCellWithReuseIdentifier:@"WCNAddCell"];
         [_collectionView registerNib:[UINib nibWithNibName:@"WCNMeetingHeaderCell" bundle:nil] forCellWithReuseIdentifier:@"WCNMeetingHeaderCell"];
        
        //注册headerView Nib的view需要继承UICollectionReusableView
        [_collectionView registerNib:[UINib nibWithNibName:@"WCNMeetingfooterBtn" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"WCNMeetingfooterBtn"];
      


    }
    return _collectionView;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.dataArray.count +2;
}
#pragma mark -加入会议的事件
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        WCNMeetingHeaderCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"WCNMeetingHeaderCell" forIndexPath:indexPath];
        cell.meetingNumber.text = _meetID;
        cell.joinBLock =^(){
        
            [self observeNetworkStatus];
        };
       
        return cell;
    }
    if (indexPath.row ==self.dataArray.count+1) {
         WCNAddCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"WCNAddCell" forIndexPath:indexPath];
        return cell;
    }
    defineWeakSelf;
    WCNMeetingPeopleCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"WCNMeetingPeopleCell" forIndexPath:indexPath];
    WCNNurseModel *model =self.dataArray[indexPath.item-1];
    NSInteger item = indexPath.item;
    cell.deleBlock =^(){
//        [weakSelf.dataArray removeObjectAtIndex:indexPath.item-1];
       
        NSLog(@"我删除了第%li",item);
         [weakSelf.dataArray removeObject:model];
        [weakSelf.collectionView performBatchUpdates:^{
            [weakSelf.collectionView deleteItemsAtIndexPaths:@[indexPath]];
        } completion:^(BOOL finished) {
            [weakSelf.collectionView reloadData];
        }];
//        [weakSelf.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    };
    cell.nameLabel.text = model.name;
    
    

    return cell;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == 0) {
        return CGSizeMake(kScreenWidth, 200);
    }
    if (indexPath.item ==self.dataArray.count+1) {
        return CGSizeMake(64, 64);
    }
    return CGSizeMake(72, 42);
}


#pragma mark -邀请按钮 ----发送邀请事件
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    weakSelf_define;
    UICollectionReusableView *view =  [collectionView dequeueReusableSupplementaryViewOfKind:kind   withReuseIdentifier:@"WCNMeetingfooterBtn" forIndexPath:indexPath];
    WCNMeetingfooterBtn *btn = (WCNMeetingfooterBtn *)view;
    btn.inviteClock =^(){
        
        if (weakSelf.dataArray.count>25) {
            WSJSHOW(@"邀请人不能超过25，请删除部分邀请人～");
            return;
            
        }
        if (weakSelf.dataArray.count==0) {
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"请先至少邀请一位与会人员" ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"好~" Click:nil];
            return;
        }
        [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"是否确认邀请" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:nil ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确认" Click:^{
            [weakSelf inviteNurse:weakSelf.dataArray];
        }];
    
    };
    
    return view;
}



-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(kScreenWidth, 64);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.item ==self.dataArray.count +1) {
        defineWeakSelf;
        WCNHospitalListVC *hospitalVC =[WCNHospitalListVC new];
        
        hospitalVC.unableSelectArray = [NSArray arrayWithArray:weakSelf.dataArray] ;
        hospitalVC.chooseType = @"inviteMeeting";
        hospitalVC.popCallBack = ^(NSArray *selectItems){
            for (WCNNurseModel *nurse in selectItems) {
                
                [weakSelf.dataArray addObject:nurse];
                            }
//
            [weakSelf.collectionView reloadData];
        
        };
        [weakSelf.navigationController pushViewController:hospitalVC animated:YES];
    }
}

//邀请护理师
- (void)inviteNurse:(NSArray *)nurses {

    
//    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
    CoreSVPLoading(@"加载中...", NO);
    NSString *nurseId = @"";
    for (WCNNurseModel *nurse in nurses) {
        nurseId = [nurseId stringByAppendingFormat:@"%@,",nurse.stringId];
        NSLog(@"%@",nurse.stringId);
    }
     Account *account =[[WCDefaultManager shareMg] account];
    NSString *content = [NSString stringWithFormat:@"%@向您发起了视频会议请求，会议号:%@",account.name,self.meetID];
   
    nurseId = [nurseId stringByReplacingCharactersInRange:NSMakeRange(nurseId.length -  1, 1) withString:@""];
    NSDictionary *param = @{@"nurseId":nurseId, @"title":@"会议邀请", @"content":content};
    [[WCNetworkAccessManager sharedMg] POST:kSendZhumuMessage parameters:param success:^(NSDictionary *result){
        
        if (result[@"data"]) {
            CoreSVPSuccess(result[@"data"]);
        }else {
            CoreSVPSuccess(@"会议邀请发送成功");
        }
    } failure:^(NSString *msg) {
        CoreSVPError(msg);
    }netError:^(id error) {
        CoreSVPError(error);
    } always:nil];
    
}

//判断当前的网络状态
- (void)observeNetworkStatus{
    
    WCNetworkAccessManager *netWork = [WCNetworkAccessManager sharedMg];
    if (netWork.netStatus == NetworkStatusWIFI) {
        [self createMeeting];
    }if (netWork.netStatus == NetworkStatusWIFI) {
        [self createMeeting];
    } else {
        if (netWork.netStatus == NetworkStatusUnknow || netWork.netStatus == NetworkStatusNO) {
            
            [JCAlertView showOneButtonWithTitle:nil Message:@"你现在的网络不可用，无法进行视频会议" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:nil];
            
        } else {
            [self alertMessage:@"你现在处于非wifi网络下，是否确定进行视频会议"];
        }
    }
}

//提示当前网络是否wifi
- (void)alertMessage:(NSString *)message {
    
    [JCAlertView showTwoButtonsWithTitle:nil Message:message ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
         [self createMeeting];
    } ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:nil];
}


@end
